// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  var crypto = require('crypto');

  var secretId = 'AKIDwgDXfZqQ4UgfPtsTFpQmruiTyHgpoTzG',
    secretKey = 'CYfYGR2SZVBIBTGo7B05FOODn8FLL6bu',
    appid = '1258450033',
    pexpired = 86400,
    userid = 0;

  var now = parseInt(Date.now() / 1000),
    rdm = parseInt(Math.random() * Math.pow(2, 32)),
    plainText = 'a=' + appid + '&k=' + secretId + '&e=' + (now + pexpired) + '&t=' + now + '&r=' + rdm + userid + '&f=',
    data = new Buffer(plainText, 'utf8'),
    res = crypto.createHmac('sha1', secretKey).update(data).digest(),
    bin = Buffer.concat([res, data]);

  var sign = bin.toString('base64');

  return {
    sign,
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}